package com.tg.paw.ums.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.paw.common.annotation.LoginAdmin;
import com.tg.paw.common.component.UserUtil;
import com.tg.paw.common.constant.CommonConstant;
import com.tg.paw.common.entity.User;
import com.tg.paw.common.entity.UserAdmin;
import com.tg.paw.common.util.CommonPageResult;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.common.util.QueryUtil;
import com.tg.paw.ums.enmus.AdminUserTypeEnum;
import com.tg.paw.ums.entity.Admin;
import com.tg.paw.ums.entity.AdminRoleRelation;
import com.tg.paw.ums.entity.Role;
import com.tg.paw.ums.params.UpdateAdminRoleParams;
import com.tg.paw.ums.service.IAdminRoleRelationService;
import com.tg.paw.ums.service.IAdminService;
import com.tg.paw.ums.service.IApiAdminService;
import com.tg.paw.ums.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员 前端控制器
 * </p>
 *
 * @author Rubble
 * @since 2020-10-21
 */
@RestController
@Slf4j
@Api(tags = "管理员管理", value = "AdminController")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IApiAdminService apiAdminService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAdminRoleRelationService adminRoleRelationService;


    @ApiOperation("根据条件分页查询管理员列表")
    @GetMapping(value = "/api/ums/admin")
    public CommonResult getAdminByPage(Admin entity,
                                           @RequestParam(value = "current", defaultValue = "1") Integer pageNo,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           @RequestParam(value = "sorter", defaultValue = "") String sorter,
                                           @RequestParam(value = "filter", defaultValue = "") String filter) {
        try {
            QueryUtil.writeEmptyString2Null(entity);
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>(entity);
            QueryUtil.buildQuery(queryWrapper,filter,sorter,Admin.class);

            return CommonPageResult.pageResult(adminService.page(new Page<>(pageNo, pageSize), queryWrapper));
        } catch (Exception e) {
            log.error("根据条件查询所有管理员：{}", e.getMessage(), e);
        }
        return CommonResult.failed();
    }

    @ApiOperation("保存管理员表")
    @PostMapping(value = "/api/ums/admin")
    public CommonResult saveAdmin(@RequestBody Admin entity,@LoginAdmin UserAdmin userAdmin) {
            try {
                if(entity.getPassword()!=null){
                    entity.setPassword(passwordEncoder.encode(entity.getPassword()));
                    if(userAdmin.getUserType() == AdminUserTypeEnum.STORE.getValue()){
                        Long parentId = userAdmin.getParentId()!=null?userAdmin.getParentId():userAdmin.getUserId();
                        entity.setParentId(parentId);
                        entity.setUserType(AdminUserTypeEnum.STORE.getValue());
                    }
                }
                if (adminService.save(entity)) {
                    return CommonResult.success();
                }
            } catch (Exception e) {
                log.error("保存管理员表：{}", e.getMessage(), e);
                return CommonResult.failed();
            }
            return CommonResult.failed();
    }

    @ApiOperation("更新管理员")
    @PutMapping(value = "/api/ums/admin/{id}")
    public CommonResult updateAdmin(@RequestBody Admin entity,@ApiParam("管理员id") @PathVariable Long id) {

        try {
            entity.setAdminId(id);
            if (adminService.updateById(entity)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("更新管理员：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("删除管理员")
    @DeleteMapping(value = "/api/ums/admin/{id}")
    public CommonResult deleteAdmin(@ApiParam("管理员id") @PathVariable Long id) {
        try {
            if (adminService.removeById(id)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("删除管理员：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("查询管理员")
    @GetMapping(value = "/api/ums/admin/{id}")
    public CommonResult getAdminById(@ApiParam("管理员id") @PathVariable Long id) {
        try {
            Admin coupon = adminService.getById(id);
            return CommonResult.success(coupon);
        } catch (Exception e) {
            log.error("查询管理员：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
    }
    @ApiOperation("查询管理员")
    @GetMapping(value = "/api/ums/adminDetail/{id}")
    public CommonResult getAdminDetailById(@ApiParam("管理员id") @PathVariable Long id) {
        try {
            Admin admin = adminService.getById(id);
            List<Role> roles = new ArrayList<>();
            if(id==CommonConstant.ADMIN_ACCOUNT_ID){
                Role role = roleService.getById(CommonConstant.ADMIN_ROLE_ID);
                roles.add(role);
            }else {
                List<AdminRoleRelation> roleRelations = adminRoleRelationService.list(Wrappers.<AdminRoleRelation>lambdaQuery().eq(AdminRoleRelation::getAdminId, id));
                List<Long> roleIds = roleRelations.stream().map(item->item.getRoleId()).collect(Collectors.toList());;

                if(CollUtil.isNotEmpty(roleIds)){
                    roles = roleService.listByIds(roleIds);
                }
            }
            admin.setRoles(roles);
            return CommonResult.success(admin);
        } catch (Exception e) {
            log.error("查询管理员：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "批量删除管理员")
    @DeleteMapping(value = "/api/ums/admin")
    public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean success = adminService.removeByIds(ids);
        return CommonResult.instance(success);
    }

    @ApiOperation(value = "当前管理员用户信息")
    @GetMapping("/api/ums/currentUser")
    public CommonResult<UserAdmin> currentUser(){
        User user = UserUtil.getLoginUser();
        UserAdmin userAdmin = null;
        if(!CommonConstant.GUEST_USER.equals(user.getUserName())){
            Admin admin = adminService.getById(user.getUserId());
            if(admin!=null){
                userAdmin = new UserAdmin();
                BeanUtils.copyProperties(admin,userAdmin);
                userAdmin.setUserName(admin.getAdminName());
                userAdmin.setUserId(admin.getAdminId());
            }
        }
        if(userAdmin==null){
            userAdmin = new UserAdmin();
            userAdmin.setUserId(user.getUserId());
            userAdmin.setUserName(user.getUserName());
        }

        return CommonResult.success(userAdmin);
    }

    @GetMapping("/api/ums/current")
    public CommonResult current(@LoginAdmin(isFull = true) UserAdmin userAdmin){

        log.info("LoginAdmin loginUsername "+JSON.toJSONString(userAdmin));

        return CommonResult.success(userAdmin);
    }

    @ApiOperation("获取管理员用户已有角色")
    @GetMapping("/api/ums/admin/roles/{adminId}")
    public CommonResult getAdminRoles(@PathVariable Long adminId){
        List<Role> roles = apiAdminService.getAdminRolesEnabled(adminId);

        return CommonResult.success(roles);
    }



    @ApiOperation("获取管理员可选角色")
    @GetMapping("/api/ums/adminRoles/selectItems")
    public CommonResult getAdminRolesSelectItems(@LoginAdmin(isFull = true) UserAdmin userAdmin){

        List<Role> roles;
        if(userAdmin.getUserType()==AdminUserTypeEnum.STORE.getValue()){
            // 店铺角色 只能获取当前店铺创建的角色
            Long merchantId = userAdmin.getParentId()!=null?userAdmin.getParentId():userAdmin.getUserId();
            roles = roleService.list(Wrappers.<Role>lambdaQuery().eq(Role::getOwner,merchantId));
            // 添加店铺管理员
            Role storeAdminRole = roleService.getById(CommonConstant.STORE_ADMIN_ROLE_ID);
            roles.add(0,storeAdminRole);
        }else {
            roles = roleService.list();
        }

        return CommonResult.success(roles);
    }

    @ApiOperation("更新管理员角色")
    @PostMapping("/api/ums/admin/roles/relation")
    public CommonResult updateAdminRole(@Valid @RequestBody UpdateAdminRoleParams params, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
        adminRoleRelationService.remove(Wrappers.<AdminRoleRelation>lambdaQuery().eq(AdminRoleRelation::getAdminId,params.getAdminId()));
        List<AdminRoleRelation> list = new ArrayList<>();
        for (Long roleId : params.getRoleIds()) {
            AdminRoleRelation entity = new AdminRoleRelation();
            entity.setAdminId(params.getAdminId());
            entity.setRoleId(roleId);
            list.add(entity);
        }
        adminRoleRelationService.saveBatch(list);

        return CommonResult.success();
    }



}
